package example;

import example.entity.Book;
import example.entity.Comment;
import example.service.BookService;
import example.service.CommentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 张心怡
 * @date 2024/12/16
 */
@WebServlet("/commentServlet")
public class CommentServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置请求编码
        request.setCharacterEncoding("UTF-8");
        int userId = Integer.parseInt(request.getParameter("user_id"));
        int bookId = Integer.parseInt(request.getParameter("book_id"));
        String message = request.getParameter("message");
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setBookId(bookId);
        comment.setMessage(message);
        comment.setDate(new java.util.Date());
        //添加评论
        CommentService.addComment(comment);

        // 可以根据需要进行页面跳转或者返回响应信息
        response.sendRedirect("commentServlet?book_id=" + bookId);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //查询图书评论
        int bookId = Integer.parseInt(request.getParameter("book_id"));
        Book bookById = BookService.getBookById(bookId);
        List<Comment> commentsByBookId = CommentService.getCommentsByBookId(bookId);
        request.setAttribute("comments", commentsByBookId);
        request.setAttribute("book", bookById);
        request.getRequestDispatcher("book_detail.jsp").forward(request, response);
    }
}